/**
 * 
 */
package lt.vin.exaatto;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * @author Vincentas
 *
 */
public class LoginTag extends TagSupport {
	
	private String url;
	
	/**
	 * @return the url
	 * @throws JspTagException 
	 */
	public String getUrl() throws JspTagException {		
		URL parsedUrl;
		
		try {
			parsedUrl = new URL(url);
		} catch (MalformedURLException e) {
			/*
			 * Assuming relative URL
			 */
			try {
				parsedUrl = new URL("http", pageContext.getRequest().getServerName(), pageContext.getRequest().getServerPort(), url);
			} catch (MalformedURLException e1) {
				throw new JspTagException(e1);
			}
		}
		
		
		return parsedUrl.toString();
	}

	/**
	 * @param url the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 7111859327729426691L;

	/* (non-Javadoc)
	 * @see javax.servlet.jsp.tagext.TagSupport#doEndTag()
	 */
	@Override
	public int doEndTag() throws JspException {
		try {
			pageContext.getOut().print("</a>");
		} catch (IOException e) {
			throw new JspTagException(e);
		}
		
		return EVAL_PAGE;
	}

	/* (non-Javadoc)
	 * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
	 */
	@Override
	public int doStartTag() throws JspException {
	    UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();
	    
	    String goTo;
	    if (user != null) {
	    	goTo = getUrl();
	    } else {
	    	goTo = userService.createLoginURL(getUrl());
	    }
	    
		try {
			pageContext.getOut().print("<a href=\"" + goTo + "\">");
		} catch (IOException e) {
			throw new JspTagException(e);
		}
		
		return EVAL_BODY_INCLUDE;
	}
}
